package com.xinou.daily_report.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xinou.common.base.config.ApiResponse;
import com.xinou.common.base.database.BasePO;
import com.xinou.common.base.exception.BusException;
import com.xinou.daily_report.PO.user.UserUpdateIconPO;
import com.xinou.daily_report.VO.MiniUserVO;
import com.xinou.daily_report.utils.DailyShiroUtil;
import com.xinou.sso.entity.SysUser;
import com.xinou.sso.enumerate.HttpSsoStatusEnum;
import com.xinou.sso.po.user.UserListPO;
import com.xinou.sso.po.user.UserUpdatePwdPO;
import com.xinou.sso.service.SysUserService;
import com.xinou.sso.util.ShiroUtil;
import com.xinou.sso.util.SsoUtil;
import com.xinou.sso.vo.user.UserListVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2021-06-11
 */
@RestController
@RequestMapping("/mini/user/")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = {"前台用户"})
public class MiniUserController {

    private final SysUserService sysUserService;

    @PostMapping("all")
    @ApiOperation(value = "全部用户列表")
    @RequiresPermissions({"mini:user:all"})
    public ApiResponse<UserListVO> userAll() {
        return new ApiResponse<>(sysUserService.userAll());
    }

    @PostMapping("updatePwd")
    @ApiOperation(value = "前台用户修改密码")
    @RequiresPermissions({"mini:user:updatePwd"})
    @ApiOperationSupport(ignoreParameters = {"po.pageNumber", "po.pageSize", "po.id"})
    public ApiResponse<Void> userUpdatePwd(@RequestBody UserUpdatePwdPO po) {
        String oldPwd = po.getOldPwd();
        String newPwd = po.getNewPwd();
        if (StrUtil.isBlank(oldPwd)) {
            throw new BusException(HttpSsoStatusEnum.RE_CODE_PWD_NO_SAME);
        }
        Long userId = ShiroUtil.getUserId();
        SysUser user = sysUserService.getById(userId);
        String pwd = new SimpleHash(Md5Hash.ALGORITHM_NAME, oldPwd, ByteSource.Util.bytes(user.getSalt()), 1).toHex();
        if (!Objects.equals(pwd, user.getPassword())) {
            throw new BusException(HttpSsoStatusEnum.RE_CODE_PWD_NO_SAME);
        }
        SsoUtil.setSaltAndPwd(user, newPwd);
        sysUserService.updateById(user);
        return new ApiResponse<>();
    }

    @PostMapping("search")
    @ApiOperation(value = "前台用户搜索")
    @RequiresPermissions({"mini:user:search"})
    public ApiResponse<UserListVO> userSearch(@RequestBody UserListPO po) {
        List<SysUser> userList = sysUserService.list(
                new LambdaQueryWrapper<SysUser>()
                        .select(SysUser::getId, SysUser::getRealName)
                        .like(StrUtil.isNotBlank(po.getRealName()), SysUser::getRealName, po.getRealName())
        );
        if (userList.isEmpty()) {
            return new ApiResponse<>(Collections.emptyList());
        }
        List<UserListVO> vos = new ArrayList<>();
        UserListVO vo;
        for (SysUser user : userList) {
            vo = new UserListVO();
            vo.setUserId(user.getId());
            vo.setRealName(user.getRealName());
            vos.add(vo);
        }
        return new ApiResponse<>(vos);
    }

    @PostMapping("/listByDept")
    @ApiOperation(value = "后台用户列表部门")
    @RequiresPermissions({"mini:user:listByDept"})
    public ApiResponse<UserListVO> userListByDept(@RequestBody BasePO po) {
        return new ApiResponse<>(sysUserService.userListByDept(po));
    }

    @PostMapping("/updateIcon")
    @ApiOperation(value = "前台用户修改头像")
    @RequiresPermissions({"mini:user:updateIcon"})
    public ApiResponse userUpdateIcon(@RequestBody UserUpdateIconPO po) {
        if (StrUtil.isBlank(po.getIcon())) {
            return new ApiResponse();
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(ShiroUtil.getUserId());
        sysUser.setIcon(po.getIcon());
        sysUserService.updateById(sysUser);
        return new ApiResponse<>();
    }

    @PostMapping("/info")
    @ApiOperation(value = "前台用户详情")
    @RequiresPermissions({"mini:user:info"})
    public ApiResponse<MiniUserVO> userInfo() {
        SysUser sysUser = sysUserService.getById(ShiroUtil.getUserId());
        MiniUserVO vo = new MiniUserVO();
        vo.setAccount(sysUser.getAccount());
        vo.setRealName(sysUser.getRealName());
        vo.setIcon(sysUser.getIcon());
        vo.setDeptId(sysUser.getDeptId());
        vo.setUserId(sysUser.getId());
        vo.setAdmin(DailyShiroUtil.roles());
        return new ApiResponse<>(vo);
    }

}

